# coding:utf-8

import requests
from .errors import GoogleTileNetworkException
import os
import logging
import conf
import time


def download_tile(x, y, z, save_path):
    url = 'http://mt2.google.cn/vt/lyrs=s&hl=zh-CN&gl=cn&x=%d&y=%d&z=%d' % (x, y, z)
    filename = '%d_%d_%d.jpg' % (x, y, z)
    try:
        r = requests.get(url, stream=True, timeout=60)  # here we need to set stream = True parameter
        r.raise_for_status()
        with open(os.path.join(save_path, filename), 'wb') as f:
            for chunk in r.iter_content(chunk_size=1024):
                if chunk:  # filter out keep-alive new chunks
                    f.write(chunk)
                    f.flush()
        return filename
    except KeyboardInterrupt:
        if os.path.exists(os.path.join(save_path, filename)):
            os.remove(os.path.join(save_path, filename))
        raise KeyboardInterrupt
    except Exception:
        raise GoogleTileNetworkException


def download_tiles(tiles, save_path, ignore_exist=True, max_downloaded=None):
    """
    tiles: list of (x, y ,z)

    new_count: 严格指新下载的图片。为何不返回已下载的图片？因为多次调用这个函数会造成已下载图片的重复计算
    """
    new_count = 0
    all_count = 0
    target_num = len(tiles)
    for i, tile in enumerate(tiles):
        x = tile[0]
        y = tile[1]
        z = tile[2]
        filename = '%d_%d_%d.jpg' % (x, y, z)
        if os.path.exists(os.path.join(save_path, filename)):
            if ignore_exist is True:
                logging.warning('%s already exists! Skipping....' % (filename))
                all_count += 1
                continue
            else:
                logging.warning('%s already exists! Set ignore_exist=True to skip.' % (filename))
        try:
            filename = download_tile(x, y, z, save_path)
            new_count += 1
            all_count += 1
        except GoogleTileNetworkException:
            logging.warning('Net error when downloading: %s' % (filename))
        if max_downloaded is not None and all_count >= max_downloaded:
            logging.warning('Achieving max_downloaded number. Breaking...')
            break
        if (i + 1) % 10 == 0:
            logging.info('%d / %d' % (i + 1, target_num))
        time.sleep(conf.DOWNLOAD_TILE_INTERVAL)
    return new_count


def download_tiles_all_count(tiles, save_path, ignore_exist=True, max_downloaded=None):
    """
    tiles: list of (x, y ,z)

    all_count: 所有下载的图片，包含之前的和后来的
    """
    new_count = 0
    all_count = 0
    target_num = len(tiles)
    for i, tile in enumerate(tiles):
        x = tile[0]
        y = tile[1]
        z = tile[2]
        if (i + 1) % 1000 == 0:
            logging.info('%d / %d' % (i + 1, target_num))
        filename = '%d_%d_%d.jpg' % (x, y, z)
        if os.path.exists(os.path.join(save_path, filename)):
            if ignore_exist is True:
                # logging.warning('%s already exists! Skipping....' % (filename))
                all_count += 1
                continue
            else:
                logging.warning('%s already exists! Set ignore_exist=True to skip.' % (filename))
        try:
            filename = download_tile(x, y, z, save_path)
            new_count += 1
            all_count += 1
        except GoogleTileNetworkException:
            logging.warning('Net error when downloading: %s' % (filename))
        if max_downloaded is not None and all_count >= max_downloaded:
            logging.warning('Achieving max_downloaded number. Breaking...')
            break
        time.sleep(conf.DOWNLOAD_TILE_INTERVAL)
    return all_count

if __name__ == '__main__':
    tiles = [(0, 0, 2), (0, 1, 2), (1, 0, 2), (1, 1, 2)]
    download_tiles(tiles, 'data/')
